package org.example.k8s_cloudplatform.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.kubernetes.client.openapi.ApiException;
import jakarta.annotation.Resource;
import org.example.k8s_cloudplatform.K8S_mapper.K8SPodMapper;
import org.example.k8s_cloudplatform.entity.Pod;
import org.example.k8s_cloudplatform.entity.PodAccess;
import org.example.k8s_cloudplatform.entity.User;
import org.example.k8s_cloudplatform.entity.res.Result;
import org.example.k8s_cloudplatform.mapper.PodAccessMapper;
import org.example.k8s_cloudplatform.mapper.PodMapper;
import org.example.k8s_cloudplatform.mapper.UserMapper;
import org.example.k8s_cloudplatform.scheduler.ExpirationScheduler;
import org.example.k8s_cloudplatform.service.Impl.PodAccessServiceImpl;
import org.example.k8s_cloudplatform.utils.CheckUtil;
import org.example.k8s_cloudplatform.utils.EmailVerifyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.IOException;
import java.util.*;

@Service
public class PodAccessService extends ServiceImpl<PodAccessMapper, PodAccess> implements PodAccessServiceImpl {

    @Resource
    private PodAccessMapper podAccessMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private K8SPodMapper k8sPodMapper;
    @Resource
    private PodMapper podMapper;

    private final Logger logger = LoggerFactory.getLogger(ExpirationScheduler.class);

    public Result viewUnauthorizedUser(Integer ownerID, Integer dockerID,String search) {
        //根据dockerID获取已授权用户ID 记为A
        List<Integer> authorizedUserIDList = podAccessMapper.selectUserIDByDockerID(dockerID);
        //获取除ownerID外的符合search前缀匹配的普通用户ID 记为B
        List<Integer> userIDList = userMapper.selectIDBySearch(search);
        Set<Integer> userIDSet = new HashSet<>(userIDList);
        userIDSet.remove(ownerID);
        //B-A 记为C
        authorizedUserIDList.forEach(userIDSet::remove);
        //根据C构造map，userID:<userID>,userName:<userName>
        List<Map<String,Object>> userInfo=new ArrayList<>();
        for(Integer userID:userIDSet){
            Map<String,Object> map=new HashMap<>();
            map.put("userID",userID);
            map.put("userName",userMapper.selectById(userID).getName());
            userInfo.add(map);
        }
        //返回结果是一个包含信息的List<Map>
        return Result.success(userInfo);
    }

    @Transactional
    public Result addAuthorizedUser(Integer ownerID, Integer dockerID, Integer userID) {
        PodAccess podAccess = new PodAccess();
        podAccess.setOwnerID(ownerID);
        podAccess.setDockerID(dockerID);
        podAccess.setUserID(userID);
        podAccess.setUserName(userMapper.selectById(userID).getName());
        podAccessMapper.insert(podAccess);
        //K8S API 调用
        Pod input = podMapper.selectById(dockerID);
        Process process;
        try {
            process=k8sPodMapper.addUser(input,userID);
            if (process != null) {
                // 等待命令执行完毕
                int exitValue = process.waitFor();
                if (exitValue != 0) {
                    logger.error(String.format("podID:%d 用户新增命令执行失败，退出值：%d", dockerID,exitValue));
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return Result.exception("权限未正确开放");
                }
            } else {
                logger.error(String.format("podID:%d 无法执行命令，Process 对象为 null", dockerID));
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.exception("权限未正确开放");
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.exception("权限未正确开放");
        } catch (ApiException e) {
            e.printStackTrace();
            System.out.println(e.getResponseBody());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.exception("权限未正确开放");
        }
        User user = userMapper.selectById(userID);
        User owner = userMapper.selectById(ownerID);
        if(user.getEmail()!=null&& CheckUtil.isEmail(user.getEmail())){
            EmailVerifyUtil.sendMailImmediately(user.getEmail(),"山东大学Docker云平台通知",
                        owner.getName()+"(账号ID:"+ownerID+")"+"已向您开放Docker(ID:" +input.getId()+")的访问权限。<br>"+
                                "连接端口: "+input.getNodePort()+"<br>" +
                                "账号: user"+userID+"<br>" +
                                "默认密码: 12345678" +"<br>" +
                                "如有疑问请联系平台管理员");
        }
        return Result.success();
    }
    @Transactional
    public Result deleteAuthorizedUser(Integer ID) {
        PodAccess input = podAccessMapper.selectById(ID);
        Pod pod = podMapper.selectById(input.getDockerID());
        Integer userID = input.getUserID();
        podAccessMapper.deleteById(ID);
        //K8S API 调用
        Process process;
        try {
            process=k8sPodMapper.deleteUser(pod,userID);
            if (process != null) {
                // 等待命令执行完毕
                int exitValue = process.waitFor();
                if (exitValue != 0) {
                    logger.error(String.format("podID:%d 用户删除命令执行失败，退出值：%d", pod.getId(), exitValue));
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return Result.exception("权限未正确回收");
                }
            }
        }catch (IOException | InterruptedException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.exception("权限未正确回收");
        } catch (ApiException e) {
            e.printStackTrace();
            System.out.println(e.getResponseBody());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.exception("权限未正确回收");
        }
        User user = userMapper.selectById(userID);
        User owner = userMapper.selectById(input.getOwnerID());
        if(user.getEmail()!=null&& CheckUtil.isEmail(user.getEmail())){
            //发送邮件
            EmailVerifyUtil.sendMailImmediately(user.getEmail(),"山东大学Docker云平台通知",
                    owner.getName()+"(账号ID:"+owner.getID()+")"+"已回收您对Docker(ID:" +pod.getId()+")的访问权限。<br>"+
                            "如有疑问请联系平台管理员");
        }
        return Result.success();
    }
}
